<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/24
 * Time: 16:37
 */
namespace app\api\controller;

use app\api\model\Login as Logins;
use think\Request;
use think\Db;
use think\Session;
use app\crypt\Wxbizdatacrypt;
use app\common\Common;

class Login extends Common
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        try{
            $list = Logins::all();
            return json($list);
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        try {
            $data   = $request->param();
            $validate = validate('Login');
            if (!$validate->check($data)) {
                return abort(409,"invalid parameter:".$validate->getError());
            }else{
                if ($_COOKIE['PHPSESSID']) {
                    session_id($_COOKIE['PHPSESSID']);
                    //获取openid和session_key
                    if(!Session::has($data['third_Session'],$this->config_session['prefix'])){
                        //'session过期了';
                        return abort(401, '登录过期');
                    }else{
                        $op = Session::get($data['third_Session'],$this->config_session['prefix']);
                        $oparr = explode('|',$op);
                        $openid = $oparr[0];

                        //数据信息解密
                        $appid = Session::get('appid',$this->config_session['prefix']);
                        $sessionKey = $oparr[1];

                        //签名验证
                        $signature2  = sha1( $data['rawData'].$sessionKey );
                        if($signature2 != $data['signature']){
                            return abort(401, '签名错误');
                        }else{
                            $encryptedData= $data['encryptedData'];
                            $iv = $data['iv'];

                            $pc = new WXBizDataCrypt($appid, $sessionKey);
                            $errCode = $pc->decryptData($encryptedData, $iv, $re );
                            $re = json_decode($re,true);
                            if ($errCode == 0) {
                                //将信息保存到数据库
                                //查询库里是否已经存在
                                $user = Db::name('user')->where(array('openid'=>$openid))->find();
                                if(empty($user)){
                                    //信息入库
                                    $insertData = array(
                                        'openid' => $openid,
                                        'session_key' => $sessionKey,
                                        'nickname'=> $re['nickName'],
                                        'gender'=>$re['gender'],
                                        'language'=>$re['language'],
                                        'city'=>$re['city'],
                                        'province'=>$re['province'],
                                        'country'=>$re['country'],
                                        'avatarUrl'=>$re['avatarUrl'],
                                        'first_visit_time' => time(),
                                        'last_visit_time' => time(),
                                        'visit_count' => 1,
                                    );
                                    $result = Logins::create($insertData);
                                }else{
                                    $count = $user['visit_count'] + 1;
                                    $updateData = array(
                                        'session_key' => $sessionKey,
                                        'nickname'=> $re['nickName'],
                                        'gender'=>$re['gender'],
                                        'language'=>$re['language'],
                                        'city'=>$re['city'],
                                        'province'=>$re['province'],
                                        'country'=>$re['country'],
                                        'avatarUrl'=>$re['avatarUrl'],
                                        'last_visit_time' => time(),
                                        'visit_count' => $count,
                                    );
                                    $result = Logins::update($updateData, ['id' => $user['id']]);
                                }
                                $u = Db::name('user')->where(array('openid'=>$openid))->find();
                                //将userid存到session里
                                $session = new Session($this->config_session);
                                $session->prefix();
                                $session->set('uid',$u['id'],$this->config_session['prefix']);
                                return json('ok');
                            } else {
                                return abort(404, $errCode);
                            }
                        }
                    }
                }else{
                    //重新登录
                    return abort(404, 'PHPSESSID不存在');
                }
            }
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        try {
            //获取appid和appsecret
            $wxconfig = Db::name('wxconfig')->find();
            $appId = $wxconfig['appid'];
            $AppSecret = $wxconfig['appsecret'];
            $authcode2Sessionhost = $wxconfig['authcode2Sessionhost'];
            $js_code = $id;
            $url = $authcode2Sessionhost.'?appid='.$appId.'&secret='.$AppSecret.'&js_code='.$js_code.'&grant_type=authorization_code';
            $res = file_get_contents($url);
            $res = json_decode($res,true);
            //自定义登录态,hmacsha256算法得到一个sign
            $api_key = $res['openid'];
            $secrity_key = $res['session_key'];
            $timestrap = time();
            $rest_api = '/login';
            $rest_uri = $rest_api."?api_key=".$api_key."&timestrap=".$timestrap;
            $sign = hash_hmac('sha256', $rest_uri, $secrity_key);
            //存入session
            //将openid和session_key存到session里
            $session = new Session($this->config_session);
            $session->prefix();
            $session->set($sign,$res['openid'].'|'.$res['session_key'],$this->config_session['prefix']);
            $session->set('appid',$appId,$this->config_session['prefix']);
            $session->set('openid',$res['openid'],$this->config_session['prefix']);
            $session->set('session_key',$res['session_key'],$this->config_session['prefix']);
            return json(['third_Session'=>$sign]);
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $data = $request->param();
            $result = Logins::update($data, ['id' => $id]);
            return json($result);
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        try {
            $result = Logins::destroy($id);
            return json($result);
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }
}